import { useState, useEffect } from 'react'
import apiService from '../utils/api.js'
import { ARTIST_GENDER_OPTIONS, ALBUM_TYPE_OPTIONS, getAlbumTypeLabel } from '../utils/constants.js'
import Pagination from './Pagination.jsx'

const AlbumsManagement = () => {
  // 专辑管理相关状态
  const [albums, setAlbums] = useState([])
  const [isAddingAlbum, setIsAddingAlbum] = useState(false)
  const [isEditingAlbum, setIsEditingAlbum] = useState(false)
  const [currentAlbum, setCurrentAlbum] = useState(null)
  const [albumFormData, setAlbumFormData] = useState({
    name: '',
    artistId: '',
    type: '',
    releaseDate: '',
    coverImageUrl: 'https://via.placeholder.com/300',
    description: ''
  })
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const [coverFile, setCoverFile] = useState(null) // 存储用户选择的封面文件
  const [artists, setArtists] = useState([]) // 存储歌手列表，用于选择专辑歌手

  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1)
  const [totalItems, setTotalItems] = useState(0)
  const [itemsPerPage, setItemsPerPage] = useState(10)

  // 获取专辑列表
  const fetchAlbums = async (page = currentPage) => {
    try {
      setLoading(true)
      const params = {
        page,
        limit: itemsPerPage
      }
      const response = await apiService.getAlbums(params)
      if (response.code === 200 && response.data) {
        setAlbums(response.data.data || [])
        setTotalItems(response.data.meta.total || 0)
      } else {
        // 如果API调不通，使用模拟数据
        setAlbums([])
        setTotalItems(0)
      }
    } catch (error) {
      console.error('获取专辑列表失败:', error)
      setError('获取专辑列表失败')
      // 使用模拟数据
      setAlbums([])
      setTotalItems(0)
    } finally {
      setLoading(false)
    }
  }

  // 获取歌手列表（用于选择专辑歌手）
  const fetchArtists = async () => {
    try {
      const response = await apiService.getArtists({ page: 1, limit: 100 })
      if (response.code === 200 && response.data) {
        setArtists(response.data.data || [])
      }
    } catch (error) {
      console.error('获取歌手列表失败:', error)
      setArtists([])
    }
  }

  // 组件首次加载时获取数据
  useEffect(() => {
    fetchAlbums()
    fetchArtists()
  }, [])

  // 处理分页变化
  const handlePageChange = (page) => {
    setCurrentPage(page)
    fetchAlbums(page)
  }

  // 准备添加专辑
  const prepareAddAlbum = () => {
    setAlbumFormData({
      name: '',
      artistId: '',
      type: '',
      releaseDate: '',
      coverImageUrl: 'https://via.placeholder.com/300',
      description: ''
    })
    setCoverFile(null) // 重置封面文件
    setIsAddingAlbum(true)
    setIsEditingAlbum(false)
    setCurrentAlbum(null)
  }

  // 准备编辑专辑
  const prepareEditAlbum = (album) => {
    setCurrentAlbum(album)
    setAlbumFormData({
      name: album.name,
      artistId: album.artistId || '',
      type: album.type || '',
      releaseDate: album.releaseDate || '',
      coverImageUrl: album.coverImageUrl || 'https://via.placeholder.com/300',
      description: album.description || ''
    })
    setCoverFile(null) // 重置封面文件
    setIsEditingAlbum(true)
    setIsAddingAlbum(false)
  }

  // 取消添加/编辑专辑
  const cancelAlbumAction = () => {
    setIsAddingAlbum(false)
    setIsEditingAlbum(false)
    setCurrentAlbum(null)
    setAlbumFormData({
      name: '',
      artistId: '',
      type: '',
      releaseDate: '',
      coverImageUrl: 'https://via.placeholder.com/300',
      description: ''
    })
    setCoverFile(null) // 重置封面文件
  }

  // 处理添加专辑
  const handleAddAlbum = async (e) => {
    e.preventDefault()
    try {
      // 先创建专辑
      const albumResponse = await apiService.addAlbum(albumFormData)
      
      // 如果用户选择了新封面，上传封面
      if (coverFile && albumResponse.code === 200 && albumResponse.data?.id) {
        try {
          const coverResponse = await apiService.uploadAlbumCover(albumResponse.data.id, coverFile)
          if (coverResponse.code !== 200) {
            console.warn('封面上传失败，但专辑创建成功')
          }
        } catch (coverError) {
          console.warn('封面上传失败，但专辑创建成功:', coverError)
        }
      }
      
      cancelAlbumAction()
      fetchAlbums()
    } catch (error) {
      console.error('添加专辑失败:', error)
      setError('添加专辑失败，请重试')
    }
  }

  // 处理编辑专辑
  const handleEditAlbum = async (e) => {
    e.preventDefault()
    try {
      if (currentAlbum) {
        // 先更新专辑信息
        await apiService.updateAlbum(currentAlbum.id, albumFormData)
        
        // 如果用户选择了新封面，上传封面
        if (coverFile) {
          try {
            const coverResponse = await apiService.uploadAlbumCover(currentAlbum.id, coverFile)
            if (coverResponse.code !== 200) {
              console.warn('封面上传失败，但专辑信息更新成功')
            }
          } catch (coverError) {
            console.warn('封面上传失败，但专辑信息更新成功:', coverError)
          }
        }
        
        cancelAlbumAction()
        fetchAlbums()
      }
    } catch (error) {
      console.error('更新专辑失败:', error)
      setError('更新专辑失败，请重试')
    }
  }

  // 处理删除专辑
  const handleDeleteAlbum = async (albumId) => {
    if (window.confirm('确定要删除这个专辑吗？')) {
      try {
        await apiService.deleteAlbum(albumId)
        fetchAlbums()
      } catch (error) {
        console.error('删除专辑失败:', error)
        setError('删除专辑失败，请重试')
      }
    }
  }

  // 处理封面上传（只做本地预览）
  const handleCoverUpload = (e) => {
    const file = e.target.files[0]
    if (!file) return
    
    // 存储选择的文件
    setCoverFile(file)
    
    // 创建本地预览URL
    const previewUrl = URL.createObjectURL(file)
    setAlbumFormData(prev => ({ ...prev, coverImageUrl: previewUrl }))
    
    // 注意：URL.createObjectURL创建的对象需要在不需要时释放，避免内存泄漏
    // 在组件卸载或选择新文件时释放
    return () => {
      if (previewUrl) {
        URL.revokeObjectURL(previewUrl)
      }
    }
  }
  
  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setAlbumFormData(prev => ({ ...prev, [name]: value }))
  }

  return (
    <>
      <div className="section-header">
        <button className="btn-add" onClick={prepareAddAlbum}>
          添加专辑
        </button>
      </div>

      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <div className="songs-table-container">
          <table className="songs-table" style={{ tableLayout: 'fixed' }}>
            <thead>
              <tr>
                <th>ID</th>
                <th>封面</th>
                <th>专辑名称</th>
                <th>歌手</th>
                <th>类型</th>
                <th>发行日期</th>
                <th style={{ width: '300px' }}>描述</th>
                <th style={{width: '200px'}}>操作</th>
              </tr>
            </thead>
            <tbody>
              {albums.map(album => {
                // 查找对应的歌手信息
                
                return (
                  <tr key={album.id}>
                    <td>{album.id}</td>
                    <td>
                      <img 
                        src={album.coverImageUrl}
                        alt={album.title} 
                        className="song-cover-small"
                      />
                    </td>
                    <td>{album.title}</td>
                    <td>{album.artist?.name || '-'}</td>
                    <td>{getAlbumTypeLabel(album.type)}</td>
                    <td>{album.releaseDate || '-'}</td>
                    <td style={{ width: '500px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{album.description || '-'}</td>
                    <td>
                      <button 
                        className="btn-edit"
                        onClick={() => prepareEditAlbum(album)}
                      >
                        编辑
                      </button>
                      <button 
                        className="btn-delete"
                        onClick={() => handleDeleteAlbum(album.id)}
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
          
          {/* 分页组件 */}
          <div className="pagination-container">
            <Pagination
              currentPage={currentPage}
              totalPages={Math.ceil(totalItems / itemsPerPage)}
              totalItems={totalItems}
              itemsPerPage={itemsPerPage}
              onPageChange={handlePageChange}
            />
          </div>
        </div>
      )}

      {/* 添加/编辑专辑表单 */}
      {(isAddingAlbum || isEditingAlbum) && (
        <div className="song-form-modal">
          <div className="song-form">
            <h3>{isAddingAlbum ? '添加专辑' : '编辑专辑'}</h3>
            <form onSubmit={isAddingAlbum ? handleAddAlbum : handleEditAlbum}>
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="albumName">专辑名称</label>
                  <input
                    type="text"
                    id="albumName"
                    name="name"
                    value={albumFormData.name}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="form-group">
                  <label htmlFor="albumArtist">歌手</label>
                  <select
                    id="albumArtist"
                    name="artistId"
                    value={albumFormData.artistId}
                    onChange={handleInputChange}
                    required
                  >
                    <option value="">请选择歌手</option>
                    {artists.map(artist => (
                      <option key={artist.id} value={artist.id}>
                        {artist.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label htmlFor="albumType">专辑类型</label>
                  <select
                    id="albumType"
                    name="type"
                    value={albumFormData.type}
                    onChange={handleInputChange}
                  >
                    {ALBUM_TYPE_OPTIONS.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label htmlFor="albumReleaseDate">发行日期</label>
                  <input
                    type="date"
                    id="albumReleaseDate"
                    name="releaseDate"
                    value={albumFormData.releaseDate}
                    onChange={handleInputChange}
                  />
                </div>
              </div>
              
              <div className="form-group">
                <label htmlFor="albumCover">封面上传</label>
                <div className="avatar-upload-container">
                  <img 
                    width={100}
                    height={100}
                    src={albumFormData.coverImageUrl}
                    alt="专辑封面预览"
                    className="avatar-preview"
                  />
                  <input
                    type="file"
                    id="albumCover"
                    onChange={handleCoverUpload}
                    accept="image/*"
                    className="avatar-upload-input"
                  />
                  <label htmlFor="albumCover" className="avatar-upload-label">
                    {isEditingAlbum ? '更换封面' : '上传封面'}
                  </label>
                </div>
              </div>
              
              <div className="form-group">
                <label htmlFor="albumDescription">描述</label>
                <textarea
                  id="albumDescription"
                  name="description"
                  value={albumFormData.description}
                  onChange={handleInputChange}
                  rows="4"
                />
              </div>
              
              <div className="form-actions">
                <button type="button" onClick={cancelAlbumAction}>取消</button>
                <button type="submit">保存</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  )
}

export default AlbumsManagement